<template>
	<view class="guest-edit flat-page">
		<!-- 2. 主内容区 -->
		<scroll-view class="main-content" scroll-y>
			<!-- 订单信息简洁展示 -->
			<view class="order-info-section">
				<text class="section-label">所属订单</text>
				<text class="order-number truncate-text">{{ selectedOrder ? selectedOrder.orderNo : '订单信息未传入' }}</text>
			</view>

			<!-- 游客表单 -->
			<view class="form-container flat-form">
				<!-- 游客姓名 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">游客姓名 <text class="required">*</text></text>
					<input class="item-input flat-input" v-model="guestForm.name" placeholder="请输入游客姓名"
						placeholder-style="color: #c0c4cc" />
				</view>

				<!-- 联系电话 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">联系电话</text>
					<input class="item-input flat-input" v-model="guestForm.phone" type="number"
						placeholder="请输入联系电话(选填)" placeholder-style="color: #c0c4cc" />
				</view>

				<!-- 身份证号 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">身份证号</text>
					<input class="item-input flat-input" v-model="guestForm.idCard" placeholder="请输入身份证号码(选填)"
						placeholder-style="color: #c0c4cc" @input="handleIdCardInput" />
				</view>

				<!-- 性别 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">性别</text>
					<view class="radio-group">
						<view class="radio-item" v-for="(gender, index) in genderOptions" :key="index">
							<view class="radio" :class="{ active: guestForm.gender === index }"
								@click="selectGender(index)">
								<view class="radio-inner" v-if="guestForm.gender === index"></view>
							</view>
							<text class="radio-label">{{ gender }}</text>
						</view>
					</view>
				</view>

				<!-- 出生日期 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">出生日期</text>
					<view class="picker-wrapper">
						<picker mode="date" @change="onBirthdayChange" :value="birthday" start="1900-01-01"
							end="2030-12-31">
							<view class="picker-display">
								{{ birthday || '请选择出生日期' }}
								<image src="/static/icons/arrow-down.png" class="arrow-icon" mode="aspectFit" />
							</view>
						</picker>
					</view>
				</view>

				<!-- 家庭住址 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">家庭住址</text>
					<input class="item-input flat-input" v-model="guestForm.address" placeholder="请输入家庭住址"
						placeholder-style="color: #c0c4cc" />
				</view>

				<!-- 紧急联系人 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">紧急联系人</text>
					<input class="item-input flat-input" v-model="guestForm.emergencyContact" placeholder="请输入紧急联系人姓名"
						placeholder-style="color: #c0c4cc" />
				</view>

				<!-- 紧急联系电话 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">紧急联系电话</text>
					<input class="item-input flat-input phone-input" v-model="guestForm.emergencyPhone" type="number"
						placeholder="请输入紧急联系电话" placeholder-style="color: #c0c4cc" />
				</view>

				<!-- 房间号（团详情页面需要） -->
				<view class="form-item flat-form-item" v-if="groupId">
					<text class="item-label flat-label">房间号</text>
					<input class="item-input flat-input" v-model="guestForm.roomNo" placeholder="请输入房间号"
						placeholder-style="color: #c0c4cc" />
				</view>

				<!-- 备注信息 -->
				<view class="form-item flat-form-item">
					<text class="item-label flat-label">备注信息</text>
					<textarea class="item-textarea flat-textarea" v-model="guestForm.remark" placeholder="请输入备注信息" 
						placeholder-style="color: #c0c4cc" rows="3" auto-height="true"></textarea>
				</view>

			</view>

			<!-- 底部占位，防止内容被底部按钮遮挡 -->
			<view class="bottom-placeholder"></view>
		</scroll-view>

		<!-- 3. 底部保存按钮 -->
		<view class="save-bottom-btn flat-bottom-btn">
			<button class="save-btn flat-btn" @click="saveGuest">{{ isAddMode ? '添加游客' : '保存修改' }}</button>
		</view>

	</view>
</template>

<script>
	import {
		getTravelerDetail,
		createTraveler,
		updateTraveler
	} from '@/https/traveler.js';
	export default {
		data() {
			return {
				// 1. 页面状态和标识
				groupId: '',
				mode: '', // add 或 edit
				guestId: '', // 游客ID，用于编辑模式

				// 2. 游客表单数据
				guestForm: {
					id: '',
					groupId: '',
					orderId: '',
					name: '',
					phone: '',
					idCard: '',
					gender: 2, // 0：男 1：女 2：未知
					birthday: null,
					address: '',
					emergencyContact: '',
					emergencyPhone: '',
					roomNo: '',
					remark: ''
				},

				// 3. 性别相关数据
				genderOptions: ['男', '女', '未知'],

				// 4. 出生日期
				birthday: '',

				// 5. 订单相关数据
				selectedOrder: null,

				// 6. 加载状态
				loading: false
			};
		},
		computed: {
			// 判断是否为添加模式
			isAddMode() {
				return this.mode === 'add';
			}
		},

		onLoad(options) {
			// 获取页面参数
			this.groupId = options.groupId || '';
			this.mode = options.mode || 'edit';
			this.guestId = options.guestId || '';
			const orderStr = options.order || '';
			const guestStr = options.guest || '';

			// 初始化表单
			this.guestForm.groupId = this.groupId;

			// 处理订单参数（如果有）
			if (orderStr) {
				try {
					const order = JSON.parse(decodeURIComponent(orderStr));
					this.selectedOrder = order;
					this.guestForm.orderId = order.id;
					this.guestForm.orderNo = order.orderNo;
				} catch (e) {
					console.error('解析订单数据失败:', e);
				}
			}

			// 优先处理完整的guest对象参数
			if (guestStr && !this.isAddMode) {
				try {
					const guestData = JSON.parse(decodeURIComponent(guestStr));
					// 填充表单数据
					this.guestForm.id = guestData.id || '';
					this.guestForm.groupId = guestData.groupId || this.groupId;
					this.guestForm.orderId = guestData.orderId || '';
					this.guestForm.name = guestData.name || '';
					this.guestForm.phone = guestData.phone || '';
					this.guestForm.idCard = guestData.idCard || '';

					// 处理性别
					if (typeof guestData.gender === 'number') {
						this.guestForm.gender = guestData.gender;
					} else if (typeof guestData.gender === 'string') {
						// 如果是字符串形式的性别（如"男"、"女"），转换为数字
						this.guestForm.gender = guestData.gender === '男' ? 0 :
							guestData.gender === '女' ? 1 : 2;
					}

					this.guestForm.birthday = guestData.birthday || null;
					this.guestForm.address = guestData.address || '';
					this.guestForm.emergencyContact = guestData.emergencyContact || '';
					this.guestForm.emergencyPhone = guestData.emergencyPhone || '';
					this.guestForm.roomNo = guestData.roomNo || '';
					this.guestForm.remark = guestData.remark || '';

					// 设置出生日期显示
					if (this.guestForm.birthday) {
						this.birthday = this.formatDateForInput(this.guestForm.birthday);
					}

					// 设置selectedOrder信息
					if (guestData.orderNo && guestData.orderId) {
						this.selectedOrder = {
							id: guestData.orderId,
							orderNo: guestData.orderNo
						};
					}
				} catch (e) {
					console.error('解析游客数据失败:', e);
					// 如果解析失败，回退到API获取
					if (this.guestId) {
						this.loadGuestById();
					}
				}
			} else if (this.isAddMode) {
				// 添加模式，直接使用上级页面传入的订单信息
			} else if (this.guestId) {
				// 编辑模式，通过ID查询游客信息
				this.loadGuestById();
			} else {
				// 既不是添加模式也没有guestId参数，返回上一页
				uni.showToast({
					title: '缺少必要参数',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		methods: {
			// 格式化日期为输入框可用格式
			formatDateForInput(dateStr) {
				if (!dateStr || dateStr === '0001-01-01T00:00:00' || dateStr === '0001-01-01 00:00:00') return '';
				try {
					// 同时处理T分隔和空格分隔的日期时间格式
					if (dateStr.includes('T')) {
						return dateStr.split('T')[0];
					} else if (dateStr.includes(' ')) {
						return dateStr.split(' ')[0];
					} else {
						return dateStr;
					}
				} catch (e) {
					return '';
				}
			},



			// 通过ID加载游客信息
			async loadGuestById() {
				if (!this.guestId) return;

				this.loading = true;
				try {


					const guestData = await getTravelerDetail({
						id: this.guestId,
					});

					if (guestData) {
						// 填充表单数据
						this.guestForm.id = guestData.id || '';
						this.guestForm.groupId = guestData.groupId || this.groupId;
						this.guestForm.orderId = guestData.orderId || '';
						this.guestForm.name = guestData.name || '';
						this.guestForm.phone = guestData.phone || '';
						this.guestForm.idCard = guestData.idCard || '';

						// 处理性别
						if (typeof guestData.gender === 'number') {
							this.guestForm.gender = guestData.gender;
						} else if (typeof guestData.gender === 'string') {
							// 如果是字符串形式的性别（如"男"、"女"），转换为数字
							this.guestForm.gender = guestData.gender === '男' ? 0 :
								guestData.gender === '女' ? 1 : 2;
						}

						this.guestForm.birthday = guestData.birthday || null;
						this.guestForm.address = guestData.address || '';
						this.guestForm.emergencyContact = guestData.emergencyContact || '';
						this.guestForm.emergencyPhone = guestData.emergencyPhone || '';
						this.guestForm.roomNo = guestData.roomNo || '';

						// 设置出生日期显示
						if (this.guestForm.birthday) {
							this.birthday = this.formatDateForInput(this.guestForm.birthday);
						}


					} else {
						uni.showToast({
							title: '获取游客信息失败',
							icon: 'none'
						});
						// 失败后返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (error) {
					console.error('加载游客信息失败:', error);
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					});
					// 失败后返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} finally {
					this.loading = false;
				}
			},



			// 出生日期变更处理
			onBirthdayChange(e) {
				this.birthday = e.detail.value;
				this.guestForm.birthday = this.birthday + 'T00:00:00';
			},

			// 性别选择方法
			selectGender(index) {
				this.guestForm.gender = index;
			},

			// 从身份证获取性别
			getGenderFromIdCard(idCard) {
				// 身份证号第17位：奇数为男，偶数为女
				if (idCard && idCard.length === 18) {
					const genderCode = parseInt(idCard.charAt(16));
					if (!isNaN(genderCode)) {
						return genderCode % 2 === 1 ? 0 : 1; // 0:男, 1:女
					}
				}
				return null; // 无法从身份证获取性别
			},

			// 处理身份证输入
			handleIdCardInput() {
				const idCard = this.guestForm.idCard.trim();
				const idCardRegex = /^\d{17}[\dXx]$/;

				// 只有当身份证格式正确时才自动填充性别
				if (idCardRegex.test(idCard)) {
					const genderFromIdCard = this.getGenderFromIdCard(idCard);
					if (genderFromIdCard !== null) {
						this.guestForm.gender = genderFromIdCard;
					}
				}
			},



			// 表单验证
			validateForm() {
				if (!this.guestForm.name.trim()) {
					uni.showToast({
						title: '请输入游客姓名',
						icon: 'none',
						duration: 2000
					});
					return false;
				}

				// 联系电话为非必填项，但如果填写了则验证格式
				if (this.guestForm.phone.trim()) {
					const phoneRegex = /^1[3-9]\d{9}$/;
					if (!phoneRegex.test(this.guestForm.phone.trim())) {
						uni.showToast({
							title: '请输入正确的手机号',
							icon: 'none',
							duration: 2000
						});
						return false;
					}
				}

				// 身份证号为非必填项，但如果填写了则验证格式
				if (this.guestForm.idCard.trim()) {
					const idCardRegex = /^\d{17}[\dXx]$/;
					if (!idCardRegex.test(this.guestForm.idCard.trim())) {
						uni.showToast({
							title: '请输入正确的身份证号',
							icon: 'none',
							duration: 2000
						});
						return false;
					}
				}

				// 紧急联系人电话验证（如果填写）
				if (this.guestForm.emergencyPhone && this.guestForm.emergencyPhone.trim()) {
					const phoneRegex = /^1[3-9]\d{9}$/;
					if (!phoneRegex.test(this.guestForm.emergencyPhone.trim())) {
						uni.showToast({
							title: '请输入正确的紧急联系电话',
							icon: 'none',
							duration: 2000
						});
						return false;
					}
				}

				return true;
			},

			// 保存游客修改
			async saveGuest() {
				// 订单信息由上级页面传入，无需验证

				// 其他表单验证
				if (!this.validateForm()) {
					return;
				}

				this.loading = true;

				try {

					// 构造游客数据，确保符合新的信息格式
					const guestData = {
						id: this.guestForm.id,
						groupId: this.guestForm.groupId,
						orderId: this.guestForm.orderId,
						name: this.guestForm.name,
						phone: this.guestForm.phone,
						idCard: this.guestForm.idCard,
						gender: this.guestForm.gender,
						// 确保日期格式正确
						birthday: this.guestForm.birthday,
						address: this.guestForm.address,
						emergencyContact: this.guestForm.emergencyContact,
						emergencyPhone: this.guestForm.emergencyPhone,
						roomNo: this.guestForm.roomNo,
						remark: this.guestForm.remark,
						orderNo: this.guestForm.orderNo,
						// 保留性别显示文本
						genderText: this.genderOptions[this.guestForm.gender]
					};

					// 根据模式调用不同的API
					let apiPromise;
					if (this.isAddMode) {
						// 添加模式
						apiPromise = createTraveler(guestData);
					} else {
						// 编辑模式
						apiPromise = updateTraveler(guestData);
					}

					// 执行API调用
					const result = await apiPromise;
					console.log(this.isAddMode ? '添加游客结果:' : '更新游客结果:', result);

					// 保存成功后返回上一页
					uni.showToast({
						title: this.isAddMode ? '添加成功' : '修改成功',
						icon: 'success',
						duration: 2000,
						success: () => {
							setTimeout(() => {
								// 返回上一页并刷新数据
								uni.navigateBack({
									delta: 1,
									success: () => {
										// 可以在这里触发上一页的数据刷新
										const pages = getCurrentPages();
										const prevPage = pages[pages.length - 2];
										if (prevPage && typeof prevPage.refreshData ===
											'function') {
											prevPage.refreshData();
										}
									}
								});
							}, 1500);
						}
					});
				} catch (error) {
					console.error(this.isAddMode ? '添加游客失败:' : '保存游客修改失败:', error);
					uni.showToast({
						title: error.message || '保存失败，请重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 返回上一页
			handleBack() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	};
</script>

<style scoped>
	@import './editGuest.css';

	
</style>